import { setToken, removeToken } from "@/util/auth";
import { setStore, getStore } from "@/util/store";
import { isURL } from "@/util/validate";
import { getRoleMenuList } from "@/const/menu";
import webiste from "@/const/website";
import {
  loginByUsername,
  getUserInfo,
  getMenu,
  logout,
  RefeshToken,
} from "@/api/user";

function addPath(ele, first) {
  const propsConfig = webiste.menu.props;
  const propsDefault = {
    label: propsConfig.label || "label",
    path: propsConfig.path || "path",
    icon: propsConfig.icon || "icon",
    children: propsConfig.children || "children",
  };
  const isChild =
    ele[propsDefault.children] && ele[propsDefault.children].length !== 0;
  if (!isChild && first) {
    ele[propsDefault.path] = ele[propsDefault.path] + "/index";
    return;
  }
  ele[propsDefault.children].forEach((child) => {
    if (!isURL(child[propsDefault.path])) {
      child[propsDefault.path] = `${ele[propsDefault.path]}/${
        child[propsDefault.path] ? child[propsDefault.path] : "index"
      }`;
    }
    addPath(child);
  });
}

function menuDataFormat(data = []) {
  if (!Array.isArray(data)) return data;
  const menuIds = data.map((ele) => {
    return ele.id;
  });

  return getRoleMenuList(menuIds);
}

const user = {
  state: {
    userInfo:
      getStore({
        name: "userInfo",
      }) || {},
    permission: {},
    roles: [],
    menu:
      getStore({
        name: "menu",
      }) || [],
    menuAll: [],
    token:
      getStore({
        name: "sessionId",
      }) || "",
    menuQueue: [],
  },
  actions: {
    //根据用户名登录
    LoginByUsername({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername(userInfo.username, userInfo.password)
          .then((res) => {
            const data = res.data.data.bussData;
            commit("SET_TOKEN", data.sessionId);
            commit("SET_USER_INFO", data);
            commit("DEL_ALL_TAG");
            commit("CLEAR_LOCK");
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //根据手机号登录
    LoginByPhone({ commit }, userInfo) {
      return new Promise((resolve) => {
        loginByUsername(userInfo.phone, userInfo.code).then((res) => {
          const data = res.data.data;
          commit("SET_TOKEN", data);
          commit("DEL_ALL_TAG");
          commit("CLEAR_LOCK");
          resolve();
        });
      });
    },
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then((res) => {
            const data = res.data.data;
            commit("SET_USERIFNO", data.userInfo);
            commit("SET_ROLES", data.roles);
            commit("SET_PERMISSION", data.permission);
            resolve(data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    //刷新token
    RefeshToken({ commit }) {
      return new Promise((resolve, reject) => {
        RefeshToken()
          .then((res) => {
            const data = res.data.data;
            commit("SET_TOKEN", data);
            setToken(data);
            resolve(data);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            console.log(1);
            commit("SET_TOKEN", "");
            commit("SET_MENU", []);
            commit("SET_ROLES", []);
            commit("DEL_ALL_TAG");
            commit("CLEAR_LOCK");
            commit("SET_USERIFNO", {});
            removeToken();
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    //注销session
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        commit("SET_MENU", []);
        commit("SET_ROLES", []);
        commit("DEL_ALL_TAG");
        commit("CLEAR_LOCK");
        removeToken();
        resolve();
      });
    },
    //获取系统菜单
    GetMenu({ commit }) {
      return new Promise((resolve) => {
        getMenu().then((res) => {
          const data = res.data.data.bussData;
          let menu = menuDataFormat(data);
          console.log(menu);
          menu.forEach((ele) => {
            addPath(ele, true);
          });
          commit("SET_MENU", menu);
          resolve(menu);
        });
      });
    },
    applyMenuQueue({ state }) {
      state.menuQueue.forEach((fn) => fn());
      state.menuQueue = [];
    },
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
      setToken(token);
    },
    SET_USERIFNO: (state, userInfo) => {
      state.userInfo = userInfo;
    },
    SET_MENU: (state, menu) => {
      state.menu = menu;
      setStore({
        name: "menu",
        content: state.menu,
        type: "session",
      });
    },
    SET_MENU_ALL: (state, menuAll) => {
      state.menuAll = menuAll;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSION: (state, permission) => {
      state.permission = {};
      permission.forEach((ele) => {
        state.permission[ele] = true;
      });
    },
    SET_USER_INFO(state, info) {
      state.userInfo = info;
      setStore({
        name: "userInfo",
        content: info,
      });
    },
    PUSH_MENU_QUEUE(state, fn) {
      if (typeof fn === "function") {
        state.menuQueue.push(fn);
      }
    },
  },
};
export default user;
